/**
 * @file	multi_role.h
 * @author	chipsea
 * @brief	This file contains the Simple BLE Peripheral sample application
 *			definitions and prototypes.
 * @version 0.1
 * @date 2020-11-30
 * @copyright Copyright (c) 2020, CHIPSEA Co., Ltd.
 * @note
 */

#ifndef MULTI_ROLE_H
#define MULTI_ROLE_H

#ifdef __cplusplus
extern "C"
{
#endif

/*********************************************************************
 * INCLUDES
 */
#include "att.h"

/*********************************************************************
 * CONSTANTS
 */


// Simple BLE Central Task Events
#define START_DEVICE_EVT                0x0001
#define START_MASTER_CONN_EVT			0x0002
#define MASTER_CONN_TIMEOUT_EVT         0x0004
#define START_LINK_STATUS_EVT           0x0008
#define START_CHAR_DATA_CHECK           0x0010
#define START_ADVERT_EVT               	0x0020
#define START_DISC_TEST_EVT				0x0040
#define BLE_AT_LINK_STATE_EVT           0x0080
#define START_SCAN_EVT                  0x0100
#define LOOP_EVT                        0x0200
#define BLE_DATA_FIFO_EVT               0x0400
#define BLE_NOTIFY_FIFO_EVT             0x0800

// add by zhufei.zhang 2018.10.25
#define PRIMARY_SERVICE_RES             5//0xFFFF
#define Characteristic_LEN              4
#define Characteristic_ValueIndex       1
#define Characteristic_NotifyIndex      2
#define Central_Test_ToDoList           6

#define BLE_NOTIFY_FIFO_LEN             1024

// Maximum number of scan responses
#define DEFAULT_MAX_SCAN_RES            20
//1主1从
#define	MAX_CONNECTION_NUM          	10 	//允许最大连接设备数量
#define	MAX_MASTER_NUM    				2   //允许最大主机数量
#define	MAX_SLAVE_NUM              	    (MAX_CONNECTION_NUM - MAX_MASTER_NUM)//允许最大从机数量

#define USER_TASK_START         0
#define USER_TASK_STOP          1

/*********************************************************************
 * MACROS
 */
typedef struct
{
	uint16 uart_service_start;
	uint16 uart_service_end;
    uint16 notify;			//handle of notify
    uint16 write;			//handle of write
	uint16 ccc;				//handle of client characteristic configuration 
} slave_handle_t;

typedef struct
{
	uint8 link_status;			//link status
	uint8 link_cmd;				//1,send cmd; 0,wait for response
	uint8 timeoutValue;			//
}LinkInitParam_t;

typedef struct
{
    uint8 PeerAddr[B_ADDR_LEN];
    uint8 PeerAddrType;
    uint8 ConnectionHandle;
    uint8 ConnectionState;		//0,disconnect; 1,connected
    uint8 ConnectionActive;		//0,disable;    1,enable
	uint8 AutoConnection;
}PeerConnectionInfo_t;

typedef enum
{
	LINK_STATUS_IDLE = 0,
    LINK_STATUS_READ_VERSION,
    LINK_STATUS_SET_DATALEN,
    LINK_STATUS_SET_PHYMODE,
    LINK_STATUS_EXCHANGE_MTU,
	LINK_STATUS_DISCOVER_SERVICE_BY_UUID,
	LINK_STATUS_DISCOVER_ALL_CHARACTER,
	LINK_STATUS_DISCOVER_ALL_CHARACTER_DESC,
    LINK_STATUS_ENABLE_NOTIFY,
	LINK_STATUS_FINISH
} link_status_t;

typedef struct
{
    uint8_t     Type;
    uint8_t     Len;
    uint8_t     Value[ATT_UUID_SIZE];
} SimpleADVServiceUUIDs;
typedef struct
{
    uint8_t     Type;
    uint8_t     Length;
    uint8_t     Value[31];      // Max PDU = 31
} SimpleADVLoaclName;
typedef struct
{
    uint16_t    ConnMin;
    uint16_t    ConnMax;
} SimpleADVSlaveInterval;
typedef struct
{
    uint8_t     Type;
    uint8_t     Len;
    uint8_t     Value[ATT_UUID_SIZE];
} SimpleADVServiceSolicitation;
typedef struct
{
    uint8_t     Length;
    uint8_t     Value[31];      // Max PDU = 31
} SimpleADVServiceDATA;
typedef struct
{
    uint8_t     Length;
    uint8_t     Value[31];      // Max PDU = 31
} SimpleADVManufactureDATA;
typedef struct
{
    uint8_t                         AddrType;
    uint8_t                         addr[B_ADDR_LEN];
    bool                            RSP_ReadFlag;
    int8                            rssi;
    int8                            TxPower;
    uint8_t                         Flags;
    SimpleADVServiceUUIDs           UUID;
    SimpleADVLoaclName              LocalName;
    uint8_t                         OOB_Data;
    uint8_t                         SM_TK_Value;
    SimpleADVSlaveInterval          ConnIntervalRange;
    SimpleADVServiceSolicitation    ServiceSolicitation;
    SimpleADVServiceDATA            ServiceData;
    SimpleADVManufactureDATA        ManufactureData;
} SimpleClientADV_ScanData;

// Service and Characteristic
typedef struct
{
    uint16_t  charStartHandle;
    uint16_t  charUuid;
    uint8_t   UUID_Len;
    uint8_t   UUID[ATT_UUID_SIZE];
    uint8_t   Properties;
} SimpleCharacteristic;
typedef struct
{
    // Service Info , User Don't Care
    uint8_t     Attribute_Data_Len;
    uint16_t    Attribute_StartHandle;
    uint16_t    End_Group_Handle;
    // User Care
    // Caculate UUID Len
    uint8_t     UUID_Len;
    uint8_t     UUID[ATT_UUID_SIZE];
    // Characteristic
    uint8_t     CharacNum;
    SimpleCharacteristic Characteristic[Characteristic_LEN];
} SimpleGATTReadGroupRsp;
typedef struct
{
    // Primary Service Num
    uint8_t                 PrimaryServiceCnt;
    // Primary Service Characteristic Index
    uint8_t                 PrimaryCharacIndex;
    // Characteristic Find Index
    uint8_t                 CharacFindIndex;
    SimpleGATTReadGroupRsp  ServerGroupService[PRIMARY_SERVICE_RES];
} SimpleGattScanServer;
/*********************************************************************
 * FUNCTIONS
 */

extern uint8 blemulti_ServiceUUID[ATT_UUID_SIZE];

///< Characteristic tx uuid
extern uint8 blemulti_TxCharUUID[ATT_UUID_SIZE];

///< Characteristic rx uuid
extern uint8 blemulti_RxCharUUID[ATT_UUID_SIZE];


extern uint8 masterLinkUUIDLen ;//主机link过程中UUID的长度，默认2字节
extern uint8 g_masterConnectNum;
extern uint8 g_slaverConnectNum;
extern uint8 g_slaveMaxNum;
extern uint8 g_masterMaxNum;
extern uint8 scanDataAddr[DEFAULT_MAX_SCAN_RES][B_ADDR_LEN];//扫描到的地址数据存在此处
extern uint8 simpleBLETaskId;
extern uint8 advertData[31];
extern uint8 simpleBLEDeviceName[31];
extern LinkInitParam_t linkInitParam[MAX_SLAVE_NUM];
extern PeerConnectionInfo_t slaveDevInfo[MAX_SLAVE_NUM];
extern PeerConnectionInfo_t masterDevInfo[MAX_MASTER_NUM];
extern attMsg_t sendMsg;//ble通道上AT回复数据缓存
extern uint8 notify_fifo[BLE_NOTIFY_FIFO_LEN];//通知缓存队列
extern uint16 notify_fifo_len;//通知缓存长度
/**
 * @brief user_data_to_slave
 * 
 */
extern slave_handle_t slave_handle[MAX_SLAVE_NUM];

/**
 * @brief findConnectIndexByConnectionHandle
 * 
 */
uint8_t findConnectIndexByConnectionHandle(uint8_t role, uint8_t connectionHandle);

/*
 * Task Initialization for the BLE Application
 */
extern void multiRoleApp_Init(uint8 task_id);

/*
 * Task Event Processor for the BLE Application
 */
extern uint16 multiRoleApp_ProcessEvent(uint8 task_id, uint16 events);

/**
 * @brief user_data_to_slave
 * 
 */
//extern bStatus_t user_data_to_slave(uint8_t masterIndex, uint8 len, uint8 *pdata);

/**
 * @brief user_task_set
 * 
 */
extern void ble_task_set(uint8 action, uint16 event, uint32 time);

extern bStatus_t linkInitProcess(uint16_t masterIndex);

extern uint16_t get_ble_tx_len_max(uint8_t role, uint8_t index);

extern bStatus_t user_data_send_by_ble(uint8_t role, uint8_t index, attMsg_t *msg);
static bool getAdtypeData(uint8 adType, uint8 *pData, uint8 dataLen, uint8 *pAdTypeData_index, uint8 *pAdTypeData_len);
char *bdAddr2Str(uint8 *pAddr);
uint8_t writeConnectIndexByAddr(uint8_t *addr);
uint8_t findConnectIndexByAddr(uint8_t role, uint8_t *addr);
uint8_t findConnectionHandleByAddr(uint8_t role, uint8_t *addr);
uint8_t getConnectRoleByAddr( uint8_t *addr);
void ble_set_master_num(uint8_t num);
void ble_set_slave_num(uint8_t num);
uint8_t ble_get_master_link_num(void);
uint8_t ble_get_slave_link_num(void);
uint8_t ble_get_master_num(void);
uint8_t ble_get_slave_num(void);
uint8_t str_to_hex(const uint8_t ch);
//bStatus_t bleuart_Notify_AT(uint8_t index, attHandleValueNoti_t *pNoti);
bStatus_t user_data_send_by_ble_at(uint8_t role, uint8_t index, attMsg_t *msg);
bStatus_t ble_link_dev(uint8_t *macAddr);
/*********************************************************************
*********************************************************************/

#ifdef __cplusplus
}
#endif

#endif /* MULTI_ROLE_H */
